import java.util.ArrayList;
import java.util.Collections;

public class SymbolTable extends ArrayList<Symbol>{
	
	SymbolTable(){
	}
	
	public void defineSymbol (Symbol symb) {
		this.add(symb);
	}
	
	public boolean symbolIsDefined(String label){	
		for(Symbol s : this){
			if(s.GetLabel().equals(label)){
				return true;
			}
		}
		return false;
	}
	
	public boolean updateLocation (String label, Integer location) {
		for(Symbol s : this){
			if(s.GetLabel().equals(label)){
				s.SetLocation(location);
				return true;
			}
		}
		return false;
	}
	
	public Symbol getSymbol (String label) {
		for(Symbol s : this){
			if(s.GetLabel().equals(label)){
				Symbol symb = new Symbol(s.GetLabel(), s.GetLocation(), s.GetUsage(), s.GetStringValue());
				return symb;
			}
		}
		Symbol symb = new Symbol();
		return symb;
	}
	
	public int getLocation (String label){
		for(Symbol s : this){
			if(s.GetLabel().equals(label)){
				return s.GetLocation();
			}
		}
		return 0;
	}
	
	public String getUsage (String label) {
		String usage = "";
		for (Symbol s : this) {
			if (s.GetLabel().equals(label)) {
				usage = s.GetUsage();
			}
		}
		return usage;
	}
	
	public String getString (String label){
		for(Symbol s : this){
			if(s.GetLabel().equals(label)){
				return s.GetStringValue();
			}
		}
		return "";
	}
	
	public void printTable(){
		Main.symbolPrint("Symbol" + '\t' + "Page" + '\t' + "Loc" + '\t' + "Usage" + '\t' + "String");
		SymbolTable LABEL_TABLE = new SymbolTable();
		
		for(Symbol s : this){
			if(s.GetUsage().equals("PRGM")){
				Main.symbolPrint(s.GetLabel() + "\t" + "0" + "\t" + Integer.toHexString(s.GetLocation()) + "\t" + s.GetUsage() + "\t" + s.GetStringValue());
			} else if(s.GetUsage().equals("LABEL")||s.GetUsage().equals("EXT")||s.GetUsage().equals("ENT")||s.GetUsage().equals("RESET")||s.GetUsage().equals("ELABEL") ){
				LABEL_TABLE.defineSymbol(s);
			}
		}
		
		Collections.sort(LABEL_TABLE);
		for(Symbol s : LABEL_TABLE){
			Main.symbolPrint(s.GetLabel() + "\t" + "0" + "\t" + Integer.toHexString(s.GetLocation()) + "\t" + s.GetUsage() + "\t" + s.GetStringValue());
		}
		
		for(Symbol s : this){
			if(s.GetUsage().equals("LITERAL")){
				Main.symbolPrint(s.GetLabel() + "\t" + "0" + "\t" + Integer.toHexString(s.GetLocation()) + "\t" + s.GetUsage() + "\t" + s.GetStringValue());
			}
		}
	}
}
